package com.cs.aspect;

import com.cs.anno.Log;
import com.cs.domain.SysLog;
import com.cs.domain.SysUser;
import com.cs.mapper.SysLogMapper;
import com.cs.mapper.SysUserMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 日志的aop
 */
@Aspect
@Component
public class LogAspect {
    @Autowired
    private SysLogMapper sysLogMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    

    /**
     * 切注解 只要加了注解就会走这个切面
     * @param joinPoint
     * @return
     */
    @Around(value = "@annotation(com.cs.anno.Log)")
    public Object LogAround(ProceedingJoinPoint joinPoint){
        //方法的标签
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        SysLog sysLog = new SysLog();
        //方法的名称
        sysLog.setMethod(method.getName());
        //用户的操作
        Log annotation = method.getAnnotation(Log.class);
        sysLog.setOperation(annotation.value());
        //方法的参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) sysLog.setParams("");
        else sysLog.setParams(joinPoint.getArgs().toString());

        //操作人的id
        String userId = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
       //登录的用户
        SysUser sysUser = sysUserMapper.selectById(Long.valueOf(userId));
        if(!ObjectUtils.isEmpty(sysUser)){
            //设置操作人的名称
            sysLog.setUsername(sysUser.getUsername());
        }
        //方法的创建时间
        sysLog.setCreateDate(new Date());
        //ip
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String ip = request.getRemoteHost();
        System.out.println(ip);
        sysLog.setIp(ip);
        //执行方法的开始时间
        long start = System.currentTimeMillis();
        Object proceed=null;
        try {
             proceed = joinPoint.proceed(joinPoint.getArgs());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        //方法的结束时间
        long end = System.currentTimeMillis();
        sysLog.setTime(end-start);
        int insert = sysLogMapper.insert(sysLog);
        return proceed;
    };



}
